const _ = require('lodash');
const foodItemModelFile = '../../app/models/foodItems.json';
const foodItemModel = require(foodItemModelFile);
const fileUtil = require("../../app/utils/fileUtil.js");

module.exports = {
    getFoodItemByName : getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    addFoodItem : addFoodItem,
    delFoodItem : delFoodItem,
    getFoodItems : getFoodItems,
    getFoodItemByNameAndProducer : getFoodItemByNameAndProducer
}

function getFoodItemByName(name, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(name, item.name)) {
            result = item;
        }
    
    })
    callback(null, result);
  
}

function getFoodItemByNameAndProducer(name, producer, callback){
    let result = null;
    _.forEach(foodItemModel, (item) =>{
        if(_.isEqual(name, item.name) && _.isEqual(producer, item.producer)){
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItemByProducer(producer, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer)) {
            result = item;
        }
    })
    callback(null, result);
}

function addFoodItem(foodItem, callback){
    let foodItems = getAllFoodItems();
    foodItems[foodItems.length] = foodItem;
    let path ='./app/models/foodItems.json';
    fileUtil.writeFile(path, JSON.stringify(foodItems));
}

function delFoodItem(itemId, callback){
    let foodItems = [];
    let length = 0;
    _.forEach(foodItemModel, (item) =>{
        if(!_.isEqual(itemId, item.itemId)){
            foodItems[length++] = item;
        }
    });
    let path ='./app/models/foodItems.json';
    fileUtil.writeFile(path, JSON.stringify(foodItems));
}

function getFoodItems(callback){
    let foodItems =  getAllFoodItems();
    callback(null, foodItems);
}


//get all food items
function getAllFoodItems(){
    let foodItems = [];
    let length = 0;
    _.forEach(foodItemModel, (item) => {
        foodItems[length++] = item;
    });
    return foodItems;
}

